package com.chengww.fingerdemo;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements PwdView.InputCallBack {

    private FingerprintCore mFingerprintCore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private PwdFragment fragment;

    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_pwd:
                intoPwdFragment();
                break;
            case R.id.btn_finger:
//                if (finger_count <= 0) {
//                    Toast.makeText(MainActivity.this, "指纹解锁超过限制", Toast.LENGTH_SHORT).show();
//                    intoPwdFragment();
//                }else {
//                    startFingerprintRecognition();
//                }
                startFingerprintRecognition();
                break;
        }
    }

    public void intoPwdFragment() {
        if (count <= 0)
            showPwdError();
        else {
            synchronized (MainActivity.class){
                Log.e("chengww",fragment.getType() +""+ !fragment.isResumed());
                if (fragment == null || fragment.getType() != 0 || !fragment.isResumed()){
                    createDialogFragment(0);
                }
            }
        }
    }

    private void createDialogFragment(int type) {
        Bundle bundle = new Bundle();
        bundle.putInt(PwdFragment.TYPE, type);
        fragment = new PwdFragment();
        fragment.setArguments(bundle);
        fragment.setPaySuccessCallBack(MainActivity.this);
        fragment.show(getSupportFragmentManager(), "Pwd");
    }

    //还可以输入密码次数
    private int count = 5;

    @Override
    public void onInputFinish(String result) {
        if (result.equals("123456")) {
            fragment.dismiss();
            Toast.makeText(this, "验证成功", Toast.LENGTH_SHORT).show();
        }else {
            showPwdError();
        }
    }

    private void showPwdError() {
        count--;
        if (count <= 0){
            showTintDialog("提示：", "密码输入达到上限", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    fragment.dismiss();
                }
            });
        }else {
            showTintDialog("密码错误","密码输入有误，你还可以输入" + count + "次",null);
        }
    }

    public void showTintDialog(String title,String msg,DialogInterface.OnClickListener listener) {
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(msg);
        builder.setCancelable(false);
        builder.setPositiveButton("确定", listener);
//        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
        builder.create().show();
    }

    /**
     * 开始指纹识别
     */
    private void startFingerprintRecognition() {
        if (mFingerprintCore == null){
            mFingerprintCore = new FingerprintCore(this);
            mFingerprintCore.setFingerprintManager(mResultListener);
        }

        if (mFingerprintCore.isSupport()) {
            if (!mFingerprintCore.isHasEnrolledFingerprints()) {
                Toast.makeText(this,"您还没有录制指纹，请录入！",Toast.LENGTH_SHORT).show();
                return;
            }
            //指纹识别已开启
            if (mFingerprintCore.isAuthenticating()) {
                createFingerFragment();
            } else {
                mFingerprintCore.startAuthenticate();
            }
        } else {
            Toast.makeText(this,"此设备不支持指纹解锁,或未开启屏幕锁",Toast.LENGTH_SHORT).show();
        }
    }

    private void createFingerFragment() {
        if (fragment == null || fragment.getType() != 1 || !fragment.isResumed()) {
            createDialogFragment(1);
        }
//        cancelAuthenticate();
    }

    /**
     * 指纹识别结果回调
     */
    private FingerprintCore.IFingerprintResultListener mResultListener = new FingerprintCore.IFingerprintResultListener() {
        @Override
        public void onAuthenticateSuccess() {
            if (fragment != null)
                fragment.dismiss();
            Toast.makeText(MainActivity.this,"指纹解锁成功",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onAuthenticateFailed(int helpId) {
            if (!fragment.setTextHint())
                Toast.makeText(MainActivity.this,"指纹解锁失败，请重试！",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onAuthenticateError(int errMsgId) {
            if (errMsgId == 7){
                Toast.makeText(MainActivity.this,"指纹解锁超过限制",Toast.LENGTH_SHORT).show();
                if (mFingerprintCore != null){
                    mFingerprintCore = null;
                }
                if (fragment != null) {
                    fragment.dismiss();
                }
                intoPwdFragment();
            }
        }

        /**
         * 开启指纹监听结果回调
         * @param isSuccess
         */
        @Override
        public void onStartAuthenticateResult(boolean isSuccess) {
            if (isSuccess) {
                createFingerFragment();
            }else
                Toast.makeText(MainActivity.this,"开启指纹监听失败",Toast.LENGTH_SHORT).show();
        }
    };

    public void cancelAuthenticate() {
        if (mFingerprintCore != null)
            mFingerprintCore.cancelAuthenticate();
    }

    @Override
    protected void onDestroy() {
        if (mFingerprintCore != null) {
            mFingerprintCore.onDestroy();
            mFingerprintCore = null;
        }

        mResultListener = null;
        super.onDestroy();
    }

}
